package com.tiny.server;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 本地环境启动类
 */
public class JettyServer {

    private static final Logger logger = LoggerFactory.getLogger(JettyServer.class);

    private static final String DEFAULT_WEBAPP_PATH = "/src/main/webapp";

    public static final String VERSION = "1.0.0";

    public static void main(String[] args) throws Exception {
        String contextPath = "/";
        int port = 60006; // 本地环境的端口

        logger.info("Starting Hands on hands REST Server...");
        logger.info("Version: " + VERSION);

        try {
            Server server = createServer(contextPath, port);
            logger.info("Jetty server created...");
            // Starting the server
            server.start();
            server.join();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(-1);
        }
    }

    /**
     * 创建server,使用开发环境的webapp路径.
     *
     * @param contextPath 资源路径
     * @param port        端口号
     * @return Jetty服务器
     */
    private static Server createServer(String contextPath, int port) throws Exception {
        Server server = new Server(port);

        String webappRootPath = JettyServer.class.getResource("/").getPath();
        webappRootPath = webappRootPath.substring(0, webappRootPath.lastIndexOf("tiny-work-server")+"tiny-work-server".length());
        WebAppContext webapp = new WebAppContext(webappRootPath + DEFAULT_WEBAPP_PATH , contextPath);

        server.setHandler(webapp);


        // 设置ssl连接器，SSL移至Nginx
       /* SslSocketConnector ssl_connector = new SslSocketConnector();
        ssl_connector.setPort(port);
        SslContextFactory cf = ssl_connector.getSslContextFactory();
        cf.setKeyStorePath("src/server/jetty/etc/keystore");
        cf.setKeyStorePassword("fangdd-customer");
        cf.setKeyManagerPassword("fangdd-customer");
        server.addConnector(ssl_connector);
        */

        return server;
    }

}
